package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.utils.HttpUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.web.editors.EditorCallback;
import cn.easyplatform.utils.SecurityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.util.Date;
import java.util.List;

public class CreateProjectView extends AbstractView<List<ProjectBean>> {
    private Textbox projectTextbox;
    private Combobox templateCombobox;
    private Textbox despTextbox;
    private Button closeBtn;
    private Button finishBtn;

    private List<ProjectBean> projectBeans;
    private String userId;
    protected CreateProjectView(Component component, EditorCallback<List<ProjectBean>> cb, String userId) {
        super(component, cb);
        this.userId = userId;
        if (cb != null)
            projectBeans = cb.getValue();
    }

    @Override
    protected void createContent(Component parent) {
        //第一个页面
        Vlayout layout = new Vlayout();
        layout.setHflex("1");
        layout.setVflex("1");
        layout.setSpacing("0");
        layout.setStyle("background: #FAFAFA;");

        Div titleDiv = new Div();
        titleDiv.setHflex("1");
        titleDiv.setHeight("74px");
        titleDiv.setStyle("text-align: center;line-height: 74px;");
        layout.appendChild(titleDiv);

        Label title = new Label(Labels.getLabel("product.apply"));
        title.setStyle("font-size:20px;padding-top: 54px;");
        titleDiv.appendChild(title);

        //
        int[] height = new int[]{34,34,62};
        String[] titles = new String[]{Labels.getLabel("editor.import.project"),
                Labels.getLabel("wiard.template"), Labels.getLabel("entity.desp")};
        String[] placeholders = new String[]{Labels.getLabel("product.create.project.name"),
                Labels.getLabel("product.create.project.template"), Labels.getLabel("product.create.project.desp")};
        for (int index = 0; index < titles.length; index++) {
            Div contentDiv = new Div();
            contentDiv.setHflex("1");
            contentDiv.setHeight("42px");
            contentDiv.setStyle("line-height: 42px;");
            layout.appendChild(contentDiv);

            Label titleLabel = new Label(titles[index]);
            titleLabel.setStyle("padding-top: 32px;padding-left: 80px");
            contentDiv.appendChild(titleLabel);

            Div cDiv = new Div();
            cDiv.setHflex("1");
            if (index == 2)
                cDiv.setVflex("1");
            else
                cDiv.setHeight(height[index] + "px");
            layout.appendChild(cDiv);

            Div textDiv = new Div();
            textDiv.setHflex("1");
            textDiv.setVflex("1");
            textDiv.setStyle("padding-top: 10px;padding-left: 65px;padding-right: 65px");
            cDiv.appendChild(textDiv);

            if (index == 0) {
                projectTextbox = new Textbox();
                projectTextbox.setVflex("1");
                projectTextbox.setHflex("1");
                projectTextbox.setPlaceholder(placeholders[index]);
                projectTextbox.setConstraint("/^[\\u4e00-\\u9fa5\\S]{1,20}$/: "+Labels.getLabel("constraint.name"));
                textDiv.appendChild(projectTextbox);
            } else if (index == 1) {
                templateCombobox = new Combobox();
                templateCombobox.setReadonly(true);
                if (projectBeans != null && projectBeans.size() > 0) {
                    for (ProjectBean projectBean : projectBeans) {
                        Comboitem comboitem = new Comboitem(projectBean.getId());
                        comboitem.setDescription(projectBean.getName());
                        comboitem.setValue(projectBean.getId());
                        comboitem.setParent(templateCombobox);
                    }
                }
                templateCombobox.setHflex("1");
                templateCombobox.setHeight("36px");
                templateCombobox.setPlaceholder(placeholders[index]);
                textDiv.appendChild(templateCombobox);
            } else {
                despTextbox = new Textbox();
                despTextbox.setHflex("1");
                despTextbox.setRows(3);
                despTextbox.setPlaceholder(placeholders[index]);
                textDiv.appendChild(despTextbox);
            }
        }

        Div buttonDiv = new Div();
        buttonDiv.setHflex("1");
        buttonDiv.setHeight("50px");
        buttonDiv.setStyle("background: white;");
        layout.appendChild(buttonDiv);

        closeBtn = new Button(Labels.getLabel("button.close"));
        closeBtn.setStyle("left: 20px;position: absolute;margin-top: 13px;");
        closeBtn.addEventListener(Events.ON_CLICK, this);
        buttonDiv.appendChild(closeBtn);

        finishBtn = new Button(Labels.getLabel("button.ok"));
        finishBtn.setStyle("right: 20px;position: absolute;margin-top: 13px;");
        finishBtn.addEventListener(Events.ON_CLICK, this);
        buttonDiv.appendChild(finishBtn);

        layout.setParent(parent);

        Window window = (Window) parent.getParent().getParent();
        window.setWidth("580px");
        window.setHeight("460px");
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (closeBtn.equals(event.getTarget())) {
            projectTextbox.getRoot().detach();
            onCloseClick(win);
        } else if (finishBtn.equals(event.getTarget())) {
            String projectID = projectTextbox.getValue();
            String templateID = null;
            String desp = despTextbox.getValue();
            if (templateCombobox.getSelectedItem() != null)
                templateID = templateCombobox.getSelectedItem().getValue();
            if (Strings.isBlank(projectID)) {
                throw new WrongValueException(projectTextbox, Labels
                        .getLabel("constraint.name"));
            }
            if (Strings.isBlank(templateID)) {
                throw new WrongValueException(templateCombobox, Labels
                        .getLabel("product.create.project.template"));
            }
            if (desp == null){
                desp = "";
            }
            StringBuilder sb = new StringBuilder();
            sb.append(templateID).append(projectID).append(desp).append(userId).
                    append(DateFormatUtils.format(new Date(), "yyyyMMdd")).append("easyplatform");
            String token = SecurityUtils.signature(sb.toString());
            JSONObject json = new JSONObject();
            json.put("name", projectID);
            json.put("desp", desp);
            json.put("templateId", templateID);
            json.put("createUser", userId);
            json.put("token", token);
            HttpUtil.getInstance().requestPostJson(StudioApp.getApiTestBaseUrl() + "/api/project/create",
                    json.toJSONString(), new HttpUtil.OnMessageListener() {
                @Override
                public void onMessage(String result) {
                    if (result == null) {
                        WebUtils.showError(Labels.getLabel("api.get.error"));
                        return;
                    }
                    JSONObject jsonObject = JSON.parseObject(result);
                    if (!jsonObject.getString("code").equals("0000")) {
                        WebUtils.showError(jsonObject.getString("data"));
                        return;
                    } else {
                        WebUtils.showSuccess(Labels.getLabel("api.create.project"));
                        projectTextbox.getRoot().detach();
                        onCloseClick(win);
                    }
                }
            });
            //Clients.evalJavaScript("copyUrl(" + textbox.getUuid() + ")");
            /*StringBuilder sb = new StringBuilder();
            sb.append("cj").append("cj1").append("demo测试").append("13799252156").append(DateFormatUtils.format(new Date(), "yyyyMMdd")).append("easyplatform");
            String api = SecurityUtils.signature(sb.toString());
            sb = new StringBuilder();
            sb.append("cj").append(DateFormatUtils.format(new Date(), "yyyyMMdd")).append("easyplatform");
            String api2 = SecurityUtils.signature(sb.toString());*/
        }
    }
}
